/**
 * 打卡设置
 */
import React from 'react';
import { Input, Form, Checkbox, Button, Row, Col, Select, Divider, Modal, Popconfirm, message } from 'antd';
import { connect } from 'umi';
// import { useDictionary } from '../hooks';
import GoogleMap from './GoogleMap';
import { EnhanceTable, ErrorBoundary } from '../components';
import Map from './Map';

// const getLocation = () => {
//     const pos = {};
//     const { geolocation } = window.navigator;
//     if (geolocation) {
//         geolocation.getCurrentPosition(findLocal, showEror);
//     }
//     function findLocal(position) {
//         pos.latitude = position.coords.latitude;
//         pos.longitude = position.coords.longitude;
//     }
//     function showEror() {
//         console.log(Error);
//     }
//     return pos;
// };

const formLayout = {
    wrapperCol: { span: 18 },
    labelCol: { span: 6 }
};

const modalFormLayout = {
    wrapperCol: { span: 20 },
    labelCol: { span: 4 }
};

const rangeOptions = [
    { label: '100米', value: 100 },
    { label: '200米', value: 200 },
    { label: '300米', value: 300 },
    { label: '500米', value: 500 },
    { label: '800米', value: 800 },
    { label: '1000米', value: 1000 },
    { label: '2000米', value: 2000 }
];

const DEFAULT_POSITION = { latitude: 24.462977, longitude: 118.143866 };

const Punch = ({ form, user, data }) => {
    const { gpsOffset, signLocations, enabledPositionOfMachine, enabledPositionOfGps, enabledPositionOfWifi } = data;
    const signWay = () => {
        const wayList = [];
        if (enabledPositionOfMachine) {
            wayList.push('1');
        }
        if (enabledPositionOfGps) {
            wayList.push('2');
        }
        if (enabledPositionOfWifi) {
            wayList.push('3');
        }
        return wayList;
    };
    const [visible, setVisible] = React.useState(false);
    const [loading, setLoading] = React.useState(false);
    const [currentRecord, setCurrentRecord] = React.useState({ ...DEFAULT_POSITION, index: -1 });
    // const [punchOptions] = useDictionary(['signWay']);
    const punchOptions = [
        {
            label: '考勤机打卡',
            value: '1'
        },
        {
            label: 'GPS打卡',
            value: '2'
        }
        // {
        //     label: 'WiFi 打卡',
        //     value: '3'
        // }
    ];
    const { signConfig = {} } = data;

    const { areaCode } = user;
    const isChinaArea = areaCode === '86';
    const MapComponent = isChinaArea ? Map : GoogleMap;
    const coordinateType = isChinaArea ? 2 : 1;

    const handleAdd = () => {
        // const { signLocations } = form.getFieldsValue();
        const list = form.getFieldValue('signLocations');
        if (list.length > 9) {
            message.warn('最多新增10个地址');
            return;
        }
        setVisible(true);
    };

    const handleEdit = (record, index) => () => {
        setCurrentRecord({ ...record, index });
        form.setFieldsValue({
            address: record.address,
            location: record.location
        });
        setVisible(true);
    };

    const handleCancel = () => {
        setVisible(false);
    };

    const handleClose = () => {
        setCurrentRecord({ ...DEFAULT_POSITION, index: -1 });
        form.setFieldsValue({
            address: '',
            location: ''
        });
        setLoading(false);
    };

    const handleOk = () => {
        if (loading) {
            return;
        }
        setLoading(true);
        const { location, address } = form.getFieldsValue();
        const list = form.getFieldValue('signLocations');
        let finalDataSource = [...list];
        if (!address) {
            message.warn('详细地址不能为空');
            setLoading(false);
            return;
        }

        const payload = {
            coordinateType,
            address,
            location,
            latitude: currentRecord.latitude,
            longitude: currentRecord.longitude
        };

        if (currentRecord.index === -1) {
            finalDataSource = [...finalDataSource, payload];
        } else {
            finalDataSource[currentRecord.index] = payload;
        }

        form.validateFields(['address'], { force: true });
        form.setFieldsValue({
            signLocations: finalDataSource
        });

        setVisible(false);
    };

    const handleDel = index => () => {
        const list = form.getFieldValue('signLocations');
        // const { signLocations } = form.getFieldsValue();
        const finalDataSource = [...list];
        finalDataSource.splice(index, 1);
        form.setFieldsValue({
            signLocations: finalDataSource
        });
    };

    const handleMapChange = ({ currentPosition, formattedAddress }) => {
        setCurrentRecord({ ...currentRecord, latitude: currentPosition.lat, longitude: currentPosition.lng });
        form.setFieldsValue({
            address: formattedAddress
        });
    };

    const handleMapSelect = name => {
        form.setFieldsValue({
            location: name
        });
    };

    const columns = [
        {
            title: '考勤地点',
            dataIndex: 'address',
            render: (text, record) => (
                <div>
                    <div>
                        <strong>{record.location}</strong>
                    </div>
                    <div>{text}</div>
                </div>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 100,
            render: (_, record, index) => (
                <span>
                    <a onClick={handleEdit(record, index)}>编辑</a>
                    <Divider type="vertical" />
                    <Popconfirm title="确定要删除吗？" onConfirm={handleDel(index)}>
                        <a>删除</a>
                    </Popconfirm>
                </span>
            )
        }
    ];

    const punchVisible = React.useMemo(() => {
        const value = form.getFieldValue('signWay') || signWay();
        return value && value.includes('2');
    }, [form, signConfig]);

    return (
        <>
            <Form {...formLayout}>
                <div style={{ width: '50%' }}>
                    <Form.Item label="打卡方式">
                        {form.getFieldDecorator('signWay', {
                            rules: [{ required: true, message: '请选择打卡方式' }],
                            initialValue: signWay()
                        })(<Checkbox.Group options={punchOptions} />)}
                    </Form.Item>
                </div>
            </Form>

            {punchVisible && (
                <Row>
                    <Col offset={3}>
                        <Button onClick={handleAdd}>添加考勤地点</Button>
                        <span style={{ padding: '0 8px 0 16px' }}>有效范围：</span>
                        {form.getFieldDecorator('gpsOffset', {
                            initialValue: gpsOffset || 100
                        })(
                            <Select style={{ width: 100 }}>
                                {rangeOptions.map(item => (
                                    <Select.Option value={item.value} key={item.value}>
                                        {item.label}
                                    </Select.Option>
                                ))}
                            </Select>
                        )}
                    </Col>
                    <Col offset={3} style={{ marginTop: 24, marginBottom: 24 }}>
                        {form.getFieldDecorator('signLocations', { initialValue: signLocations || [] })(
                            <EnhanceTable
                                columns={columns}
                                pagination={false}
                                rowKey="id"
                                size="small"
                                style={{ maxWidth: 700 }}
                            />
                        )}
                    </Col>
                </Row>
            )}

            <Modal
                title="考勤地点"
                visible={visible}
                onCancel={handleCancel}
                afterClose={handleClose}
                confirmLoading={loading}
                onOk={handleOk}
                width="800px"
                destroyOnClose
                centered
            >
                <Form {...modalFormLayout}>
                    <div style={{ width: '100%', height: '400px', marginBottom: 24 }}>
                        <ErrorBoundary>
                            <MapComponent
                                defaultPosition={{ lat: currentRecord.latitude, lng: currentRecord.longitude }}
                                onChange={handleMapChange}
                                onSelect={handleMapSelect}
                                visible={visible}
                            />
                        </ErrorBoundary>
                    </div>
                    <Form.Item label="详细地址">
                        {form.getFieldDecorator('address')(
                            <Input style={{ border: 'none', paddingLeft: 0, boxShadow: 'none' }} readOnly />
                        )}
                    </Form.Item>
                    <Form.Item label="地点备注名" help="备注名会显示于手机端的打卡界面，便于员工在打卡时识别地址">
                        {form.getFieldDecorator('location')(<Input maxLength={50} />)}
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default connect(({ user }) => ({ user: user.currentUser }))(Punch);
